from rest_framework import mixins
from rest_framework.pagination import PageNumberPagination
from rest_framework import viewsets
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from .filter import GoodsFilter


from .models import Goods, GoodsCategory, HotSearchWords,Banner
from .serializesr import GoodsSerializers, GoodsCategorySerializers, HotWordsSerializer,BannerSerializer,NewGoodsSerializer



class GoodsPagination(PageNumberPagination):
    """
    自定商品义分页
    """
    page_size = 12  # 每页10条
    page_size_query_param = 'page_size'  # 设置每页为上面的变量也就是十条
    max_page_size = 50  # 最多50条


class GoosdListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    搜索
    """
    queryset = Goods.objects.all()  # 查询该模型所有数据
    serializer_class = GoodsSerializers  # GoodsSerializers序列化
    pagination_class = GoodsPagination  # 设置自定义分页
    # DjangoFilterBackend配置过滤器,SearchFilter搜索OrderingFilter排序
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filterset_class = GoodsFilter  # 配置写好过滤规则的类
    search_fields = ('name', 'goods_brief', 'is_hot',)  # 搜索字段
    ordering_fields = ('sold_num', 'market_price',)  # 根据某字段排序


class GoodsCategoryViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    list:
        获取商品列表
    retrieve:
        获取商品分类详情
    """
    queryset = GoodsCategory.objects.filter(category_type=1)  # 过滤掉category_type是1 的数据
    serializer_class = GoodsCategorySerializers  # 序列化模型


class HotSearchsViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    获取热搜商品
    """
    queryset = HotSearchWords.objects.all().order_by("-index")
    serializer_class = HotWordsSerializer


class BannerCarouselViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    首页轮播图
    """
    queryset = Banner.objects.filter().order_by('index')
    serializer_class = BannerSerializer

class NewGoodsViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    新品
    """
    queryset = Goods.objects.filter(is_new=True)
    serializer_class = NewGoodsSerializer

